/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.User;
import com.sesame.service.UserService;
import com.sesame.toolkit.Encrypt;

/**
 * @author shubeta
 * 
 */
public class RegisterController extends SimpleFormController {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        String identifyCode = request.getParameter("identifyCode");
        String confirmPassword = request.getParameter("confirmPassword");
        User user = (User) command;

        Date regTime = new Date();
        Date lastLogin = regTime;
        user.setRegTime(regTime);
        user.setLastLogin(lastLogin);
        user.setGender("0");
        user.setHeadPic(Encrypt.MapEncrypt("00000/000"));

        Map model = errors.getModel();
        model.put("user", user);

        boolean isRightCode = userService.validateCode(request, identifyCode,
                model);
        boolean isRightPassword = userService.validatePassword(user,
                confirmPassword, model);
        boolean isRegister = false;

        if (isRightCode && isRightPassword) {
            isRegister = userService.register(request, user, model);
        }

        if (isRegister) {
            return new ModelAndView("redirect:login.html");
        } else {
            return new ModelAndView(getFormView(), model);
        }

    }

}